package com.example.springboot.modules.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.springboot.globalutils.BizException;
import com.example.springboot.modules.mybatis.entity.AccountsEntity;
import com.example.springboot.modules.mybatis.service.AccountsService;
import com.example.springboot.modules.security.entity.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Set;

@Service("userDetailsService")
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    //密码加密
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AccountsService accountsService;

    //自定义认证 及获取权限
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        log.info("自定义认证开始，userName={}",userName);
        //根据用户名获取
        AccountsEntity account = accountsService.getOne(new LambdaQueryWrapper<AccountsEntity>()
                .eq(AccountsEntity::getUserName, userName));
        if (Objects.isNull(account)){
            throw new BizException(403,"用户不存在");
        }
        //根据用户信息获取 角色 权限信息(此处模拟)
        String auth = "Role_admin,web";
        List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(auth);
        //将查询出来的用户信息及角色，权限信息set到security框架的User对象中
        log.info("自定义认证结束，auth={}",auth);
//        return new User(account.getUserName(),passwordEncoder.encode(account.getPassword()),grantedAuthorities);
        return new LoginUser(account,grantedAuthorities);
    }
}
